<template>
	<div class="xy-map">
		<div class="xy-map__search">
			<el-input
				v-model="searchValue"
				placeholder="请输入地址进行搜索"
				@change="confirmMap"
			></el-input>
			<el-button icon="el-icon-search" type="info" plain @click="confirmMap">搜索</el-button>
			<el-button type="info" @click="save">保存</el-button>
		</div>
		<div id="GDMap"></div>
	</div>
</template>
 
<script>
export default {
	name: 'xy-map',
	props: {
		lnglat: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			map: '' /* 地图实例 */,
			marker: '' /* 地图点标记 */,
			longitude: '' /* 经度 */,
			latitude: '' /* 纬度 */,
			address: '' /* 详细地址 */,
			province: '' /* 省 */,
			city: '' /* 市 */,
			searchValue: '' /* 搜索关键字 */
		};
	},
	watch: {
		lnglat(val) {
			if (val && val.length > 0) {
				this.setPoint({
					lnglat: {
						lng: val[0],
						lat: val[1]
					}
				});

				setTimeout(() => {
					this.map.setCenter([val[0], val[1]]);
				}, 300);
			} else {
				this.map.clearMap();
				this.longitude = '';
				this.latitude = '';
				this.address = '';
				this.marker = '';
				this.searchValue = '';
			}
		}
	},
	mounted() {
		this.init();
	},
	methods: {
		// 初始化
		async init() {
			if (this.lnglat && this.lnglat.length > 0) {
				this.longitude = this.lnglat[0];
				this.latitude = this.lnglat[1];
			}

			this.initMap();
		},

		initMap() {
			let self = this;
			this.$nextTick(() => {
				setTimeout(() => {
					if (!self.map) {
						self.map = new AMap.Map('GDMap', {
							viewMode: '2D', // 默认使用 2D 模式，如果希望使用带有俯仰角的 3D 模式，请设置 viewMode: '3D',
							zoom: 13, //初始化地图层级
							resizeEnable: true
						});

						if (self.longitude && self.latitude) {
							setTimeout(() => {
								self.map.setCenter([self.longitude, self.latitude]);
							}, 300);

							// 构造点标记
							this.marker = new AMap.Marker({
								icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
								position: [self.longitude, self.latitude],
								anchor: 'bottom-center'
							});

							this.getAddress([self.longitude, self.latitude]);
							this.map.add(this.marker);
						}

						self.map.on('click', self.setPoint);
					}
				});
			});
		},

		// 地图标点
		setPoint(e) {
			this.map.remove(this.marker);

			// 构造点标记
			this.marker = new AMap.Marker({
				icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
				position: [e.lnglat.lng, e.lnglat.lat],
				anchor: 'bottom-center'
			});

			this.getAddress([e.lnglat.lng, e.lnglat.lat]);

			this.map.add(this.marker);
		},

		// 根据坐标返回地址(逆地理编码)
		getAddress(points, address = '') {
			let self = this;

			AMap.plugin('AMap.Geocoder', function () {
				let geocoder = new AMap.Geocoder({ radius: 1000 });
				geocoder.getAddress(points, (status, result) => {
					if (status === 'complete' && result.regeocode) {
						let s_addr =
							result.regeocode.addressComponent.province +
							result.regeocode.addressComponent.city +
							result.regeocode.addressComponent.district;
						let addreesd = ''; // 全部地址名称

						if (address) {
							addreesd = s_addr + address;
						} else {
							addreesd = result.regeocode.formattedAddress;
						}

						self.address = addreesd;
						self.latitude = points[1];
						self.longitude = points[0];
						self.province = result.regeocode.addressComponent.province;

						if (
							self.province == '重庆市' ||
							self.province == '天津市' ||
							self.province == '上海市' ||
							self.province == '北京市'
						) {
							self.city = result.regeocode.addressComponent.province;
						} else {
							self.city = result.regeocode.addressComponent.city;
						}

						self.area = result.regeocode.addressComponent.district;
						self.openInfo(points, addreesd);
					}
				});
			});
		},

		openInfo(points, addreesd) {
			//构建信息窗体中显示的内容
			var info = [];

			info.push(`<p class='input-item'>地址 :${addreesd}</p></div></div>`);

			let infoWindow = new AMap.InfoWindow({
				anchor: 'top-center',
				content: info.join('') //使用默认信息窗体框样式，显示信息内容
			});

			infoWindow.open(this.map, points);
		},

		save() {
			if (this.address) {
				this.$emit('change', {
					lng: this.longitude,
					lat: this.latitude,
					address: this.address
				});
			} else {
				this.$message.error('请至少标记一个点位');
			}
		},

		// 地图确定搜索
		confirmMap() {
			let self = this;

			if (!this.searchValue) {
				this.$message.warning('请输入搜索地址');
			} else {
				// 获取搜索信息
				var keywords = this.searchValue;
				AMap.plugin('AMap.PlaceSearch', function () {
					var autoOptions = {
						city: '全国'
					};
					var placeSearch = new AMap.PlaceSearch(autoOptions);
					placeSearch.search(keywords, function (status, result) {
						// 搜索成功时，result即是对应的匹配数据
						self.map.remove(self.marker);

						let lng = result.poiList.pois[0].location.lng;
						let lat = result.poiList.pois[0].location.lat;

						// 构造点标记
						self.marker = new AMap.Marker({
							icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
							position: [lng, lat],
							anchor: 'bottom-center'
						});

						setTimeout(() => {
							self.map.setCenter([lng, lat]);
						}, 500);

						self.map.add(self.marker);
						self.getAddress([lng, lat], result.poiList.pois[0].name);
					});
				});
			}
		}
	}
};
</script>
 
<style lang="scss">
.xy-map {
	box-sizing: border-box;
	height: 100%;

	&__search {
		margin-bottom: 20px;
		display: flex;
		justify-content: center;
		align-items: center;

		button {
			margin-left: 10px;
		}
	}

	#GDMap {
		height: calc(100% - 60px);
		width: 100%;
	}
}
</style>